package com.kuang.cas;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

// 模拟CAS出现的ABA问题
public class Test2 {
    public static void main(String[] args) throws InterruptedException {
        AtomicInteger atomicInteger = new AtomicInteger(1);

        // 线程A：捣乱的线程，修改下，又修改回去
        new Thread(()->{
            // 如果原子Integer类值和预期值一样，就更新
            System.out.println(atomicInteger.compareAndSet(1, 2));
            System.out.println(atomicInteger.get());
            System.out.println(atomicInteger.compareAndSet(2, 1));
            System.out.println(atomicInteger.get());
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 线程B
        new Thread(()->{
            System.out.println(atomicInteger.compareAndSet(1, 6));
            System.out.println(atomicInteger.get());
        }).start();


        /*
            true
            2
            true
            6
            停顿5s后
            true
            6
         */
    }
}
